import React, {useContext} from "react";
import {BrowserRouter as Router, Switch, Route, Redirect, useHistory} from "react-router-dom";

import {AuthContext, AuthProvider} from './auth-context';

import {Login, Reg, Home} from './routes';

import './App.css';

function SecuredRoute () {

  const {checkSession} = useContext(AuthContext);

  return (
    <Route path='/*' render={
      () => checkSession() ? <Home /> : <Redirect to='/login' />
    } />
  )
}

const Routes = () => {

  const history = useHistory();

  return (
    <Router history={history}>
      <AuthProvider>
        <Switch>
          <Route path="/reg" component={Reg} />
          <Route path="/login" component={Login} />
          <SecuredRoute />
        </Switch>
      </AuthProvider>
   </Router>
  );
};

const App = () => {
  return (
    <div className="App">
      <Routes />
    </div>
  );
}

export default App;
